<template>
	<view class="xzdd_content">
		<!-- 头部 -->
		<view class="xzdd_header">
            <view class="xzdd_header_top">
				
				<uni-row class="form_row">
					<uni-col class="form_item" :span="10">
						<view>查看日期：</view>
						<uni-datetime-picker :border="false" v-model="formData.datetimerange" type="datetimerange" rangeSeparator="至" @change="changeTimer" />
					</uni-col>

					<uni-col class="form_item" :span="14">
							<input style="flex: 1; margin-left: 40rpx;" type="text" v-model="formData.searchKey" placeholder="货号/品名检索" />
							<button hover-class="hover_btn" @click="handleSearch">查询</button>
					</uni-col>
				</uni-row>
			</view>

			<view class="header_amount">
				<view class="amount_item" v-for="(item, index) in amountList" :key="index">
					<view class="amount_name"> {{ item.name }}</view>
					<view> {{ item.sl }}</view>
					<view v-if="index != amountList.length - 1" class="amount_line"></view>
				</view>
			</view>

			<view class="xzdd_fliter">
				<checkbox-group @click="selectAll">
					<label style="display: flex; align-items: center;" >
						<checkbox value="cb" :checked="showAll" />全选
					</label>
				</checkbox-group>
				<view class="amount_num">
					已选：
					<text> {{ksSl || 0}}</text>
					款/
					<text> {{totalSl || 0}}</text>
					件
				</view>
				<uni-segmented-control v-if="showFhType" class="segmented" :current="current" :values="items" @clickItem="onClickItem" styleType="button" activeColor="#ff8800"></uni-segmented-control>
			</view>

			<view class="header_btns">
				<button hover-class="hover_btn" @click="handleSave">确认</button>
			</view>
		</view>
		<!--  -->

		<view class="xzdd_list">
			<scroll-view style="height: 100%;" scroll-y="true">
				<!--  -->
				<view v-if="current == 0" class="billing_item" v-for="(item, index) in list" :key="index">
					<view class="billing_info">
						<view class="billing_img">
							<checkbox-group @click="selectFpCheck(item)">
								<label style="display: flex; align-items: center;">
									<checkbox value="xx" :checked="item.check" />
									<view style="width: 100rpx; height: 100rpx;">
										<image style="height: 100%; width: 100%; border-radius: 10rpx;" :src="item.main.image" />
									</view>
								</label>
							</checkbox-group>
						</view>

						<view class="info_center">
							<view class="info_center_row">
								<view style="width: 33%;">货号: {{ item.main.bbreed || '' }}</view>
								<view style="width: 33%;">品名: {{ item.main.description || '' }}</view>
								<view style="width: 34%;">订单号: {{ item.main.dh || '' }}</view>
							</view>

							<view class="info_center_row">
								<view style="width: 33%;">数量: {{ item.main.xdsl || 0 }}</view>
								<view style="width: 33%;">已发货: {{ item.main.yfhsl || 0 }}</view>
								<view style="width: 34%;">未发货：{{ item.main.wfhsl || 0 }}</view>
							</view>
							<view class="info_center_row">
								<view style="width: 100%;" class="info_item">备注: {{ item.main.remark || '' }}</view>
							</view>
						</view>

						<view  @click="item.showTable = !item.showTable" style="display: flex; align-items: flex-end;">
							{{ !item.showTable ? '查看详情 >>' : '收起 >>' }}
						</view>
					</view>

					<view v-if="item.showTable" style="padding-top: 20rpx;">
						<view>
							<uni-table border stripe emptyText="暂无更多数据"  >
								<uni-tr>
									<uni-th  width="110" align="center"></uni-th>
									<uni-th align="center" v-for="(j, i) in item.colorTable[0].chima" :key="i">
										{{ i }}
									</uni-th>
								</uni-tr>
								<uni-tr v-for="(x, y) in item.colorTable" :key="y">
									<uni-td align="center" v-if="x.hj != 0">{{ x.color }}</uni-td>
									<uni-td align="center" v-if="x.hj != 0" v-for="(w, v) in x.chima" :key="v"> 
										{{ w }}
									</uni-td>
								</uni-tr>

							</uni-table>
						</view>
					</view>
				</view>
				<!--  -->

				<view v-if="current == 1" class="zdfh_list" v-for="(item, index) in list" :key="index">
					<view class="zdfh_header" >
						<checkbox-group @click=selectFpCheck(item)>
							<label style="display: flex; align-items: center;" >
								<checkbox value="cb" :checked="item.check" />
								<view style="margin: 10rpx 20rpx;">单号：{{ item.dhinfo.dh || '' }}</view>
							</label>
						</checkbox-group>
						<view>日期：{{ item.dhinfo.zhdate || '' }}</view>
					</view>

					<view style="padding-left: 20rpx;">
						<!--  -->
						<view v-for="(i, j) in item.dataList" :key="j">
							<view class="billing_item" >
								<view class="billing_info">
									<view class="billing_img">
										<view style="width: 100rpx; height: 100rpx;">
											<image style="height: 100%; width: 100%; border-radius: 10rpx;" :src="i.main.image" />
										</view>
									</view>

									<view class="info_center">
										<view class="info_center_row">
											<view style="width: 33%;">货号: {{ i.main.bbreed || '' }}</view>
											<view style="width: 33%;">品名: {{ i.main.description || '' }}</view>
											<view style="width: 34%;">订单号: {{ i.main.dh || '' }}</view>
										</view>

										<view class="info_center_row">
											<view style="width: 33%;">数量: {{ i.main.xdsl || 0 }}</view>
											<view style="width: 33%;">已发货: {{ i.main.yfhsl || 0 }}</view>
											<view style="width: 34%;">未发货：{{ i.main.wfhsl || 0 }}</view>
										</view>
										<view class="info_center_row">
											<view style="width: 100%;" class="info_item">备注: {{ i.main.remark || '' }}</view>
										</view>
									</view>

									<view  @click="handleTable(i)" style="display: flex; align-items: flex-end;">
										{{ !i.showTable ? '查看详情 >>' : '收起 >>' }}
									</view>
								</view>

								<view v-if="i.showTable" style="padding-top: 20rpx;">
									<view>
										<uni-table border stripe emptyText="暂无更多数据"  >
											<uni-tr>
												<uni-th  width="110" align="center">颜色/尺码</uni-th>
												<uni-th align="center" v-for="(j, i) in i.colorTable[0].chima" :key="i">
													{{ i }}
												</uni-th>
											</uni-tr>
											<uni-tr v-for="(x, y) in i.colorTable" :key="y">
												<uni-td align="center" v-if="x.hj != 0">{{ x.color }}</uni-td>
												<uni-td align="center" v-if="x.hj != 0" v-for="(w, v) in x.chima" :key="v"> 
													{{ w }}
												</uni-td>
											</uni-tr>

										</uni-table>
									</view>
								</view>
							</view>

						</view>
						
						<!--  -->
					</view>


				</view>
			</scroll-view>
		</view>


		
	</view>
</template>

<script>
import customHeader from "@/components/custom-header/custom-header.vue";
import utils from "@/utils/utils.js";
import GetDate from "@/utils/date.js";
import Http from '@/service/api'
	export default {
		components: {
			customHeader,
        
		},
		data() {
			return {
				form: {},
				filtrList: [
                    { value: 0, text: "默认排序" },
                    { value: 1, text: "订量多到少" },
                    { value: 2, text: "订量少到多" },
                    { value: 3, text: "价格高到低" },
                    { value: 4, text: "价格低到高" },
                ],
				amountList: [
					{ name: '未发订单数', sl: '0' },
					{ name: '订单数', sl: 0 },
					{ name: '未发数量', sl: 0 },
					{ name: '未发金额', sl: '￥ 0' },
				],
				formData: {
					searchKey: '',
				}, 

				current: 0,
				fhType: -1, //
				showFhType: true,
				items: ['分批发货', '整单发货'],
				list: [],

				fpfhList: [],
				showAll: false, // 是否全选
				ksSl: 0,
				totalSl: 0,
				khInfo: {},
			}
		},
        computed: {},
		watch: {
			list: {
				handler(newVal) {
					console.log('== newVal', newVal)
					let b = this.calculateTotal(newVal)
					console.log('== b ', b)
					this.ksSl = b.ksSl
					this.totalSl = b.totalSl
				},
				deep: true,
				immediate: true
			}
		},
		onLoad(r) {
			if (r.hasOwnProperty('fhType')) {
				console.log('== onLoad ', r)	
				this.fhType = r.fhType
				this.khInfo = JSON.parse(r.khInfo)
				if (r.fhType == 0) {
					this.current = 0
					this.showFhType = false
				} else if (r.fhType == 1 ) {
					this.current = 1
					this.showFhType = false
				} else if (r.fhType == -1) {
					this.showFhType = true
				}

			}

			let today = GetDate.getToday().time
			this.formData.dates = today.slice(0, 8) + '01'
			this.formData.datee = today
			this.formData.datetimerange = [this.formData.dates, today]

			let aa  = utils.getTableData()

			console.log('== aa ', aa)

			this.selectWfhOrderList()
		},
		methods: {
			selectAll() {
				this.showAll = !this.showAll
				let arr = [...this.list]
				this.list = arr.map(i => ({
					...i,
					check: this.showAll
				}))
			},
			handleTable(item) {
				let arr = JSON.parse(JSON.stringify(this.list))
				this.list = arr.map((i , m)=> ({
					...i,
					dataList: i.dataList.map((j , n)=> {
						return {
							...j,
							showTable: j.uuid == item.uuid ? !j.showTable : j.showTable
						}
					})
				}))
			},
			selectFpCheck(item) {
				let arr = [...this.list]
				this.list = arr.map(i => ({
					...i,
					check: item.uuid == i.uuid ? !i.check : i.check
				}))

			},
			onScrolltolower() {
				console.log('== 触底')
			},

			onClickItem(e) {
				console.log('== e', e)
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
				this.showAll = false
				this.selectWfhOrderList()
			},
			handleSave() {
				console.log('== 订单确认 ', this.list)
				let arr = []
				if (this.current == 0) {
					arr = this.list.filter(i => i.check)
					
				} else {
					arr = this.list.filter(i => i.check)
				}
				console.log('== 选中 ', arr)
				

				if(!arr.length) {
					uni.showToast({
						title: '请选择订单',
						icon: 'none'
					})
					return
				}
				uni.redirectTo({
					url: `./xsfhd?fhType=${this.current}&list=${JSON.stringify(arr)}&khInfo=${JSON.stringify(this.khInfo)}`
				})
			},

			handleSearch() {
				console.log('== 11 formData ', this.formData)
				this.selectWfhOrderList()
			},
			
			selectWfhOrderList() {
				const { dates, datee, searchKey } = this.formData
				console.log('== current ', this.current)
				let param = {
					dates,
					datee,
					searchKey,
					sendType: !this.current ? '分批发货' : '整单发货',
					khid: this.khInfo.bh
				}
				console.log('== 11 ', param)
				Http.selectWfhOrderList(JSON.stringify(param)).then(r => { 
                   this.amountList = [
					{ name: '未发订单数', sl: r.forminfo.huohaocount },
					{ name: '订单数', sl: r.forminfo.wfh_ddsl },
					{ name: '未发数量', sl: r.forminfo.wfh_xs },
					{ name: '未发金额', sl: `￥ ${r.forminfo.wfh_je || 0}` },
				   ]

				   let list = []
				   
				   if (this.current == 0) {
						list = r.fpfhList
						this.list = this.filterCheckFn(list)
						
					} else {
						// list = r.zcfhList
						list = r.zcfhList.map(i => ({
							...i,
							check: false,
							dataList: this.filterCheckFn(i.dataList),
							uuid: this.guid()
						}))
						this.list = list

						console.log('== this.list ', this.list)

						// list.forEach(item => {
						// 	item.dataList.forEach(i => {
						// 		console.log('== i ', i)
						// 		i.colorList.forEach(x => {
						// 			console.log('== xx ', x)
						// 		})
						// 	})
						// })
				   }


                }).catch(err => {
                    console.log('== err ', err)
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
                })
			},
			changeTimer(e) {
				if (!e.length) return
				this.formData.dates = e[0].slice(0, 10)
				this.formData.datee = e[1].slice(0, 10)
			},

			// 、、、、、、、、、、、、、、、
			filterCheckFn(arr) {
                arr.forEach(item => {
                    // 遍历 colorList
                    item.colorList.forEach(colorItem => {
                        // 遍历 colorItem.chimaList
                        colorItem.num =  colorItem.chimaList.reduce((sum, chima) => sum + chima.num, 0);
                    });
                    

                    item.colorList = item.colorList.filter(i => !i.chimaList.every(j => j.num == 0))

                    item.colorList = item.colorList.filter(i => i.chimaList.length)
                    item.showTable = false
                    item.colorTable = this.transformArr(item.colorList)

                    // 更新 hjsl（colorList 中所有 num 的总和）
                    item.hjsl = item.colorList.reduce((total, color) => total + color.num, 0);

                    // 更新 hjPrice（hjsl * xsprice）
                    item.hjPrice = item.hjsl * item.main.price;
					item.check = false
					item.uuid = this.guid()
                });
                // 删除 colorList 为空的对象

                let a = arr.filter(item => item.colorList.length)
                return a;
            },
			calculateTotal(arr) {
                let totalSl = 0;
                let ksSl = 0;
				let ksList = []

				if (this.current == 1) {
					arr.forEach(item => {
						if (item.check) {
							item.dataList.forEach(j => {
								totalSl+= j.main.wfhsl
								ksList.push(j.main.bbreed)
							})
						}
					});
				} else {
					arr.forEach(item => {
						if (item.check) {
							totalSl+= item.main.wfhsl
							ksList.push(item.main.bbreed)
						}
					});
				}
				ksSl = [...new Set(ksList)].length

                // 返回最终的总和
                return { totalSl, ksSl};
            },
			guid() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			// 将数组 转换成 table 形式
            transformArr(arr) {
                return arr.map(item => {
                    // 创建一个新的对象
                    let transformedItem = {
                        hj: item.num,  // 直接提取 num 作为 hj
                        color: item.color,
                        chima: {}  // 初始化一个空对象，用于存放尺寸和对应的数量
                    };

                    // 遍历 chimaList，并填充 transformedItem.chima
                    item.chimaList.forEach(chima => {
                        transformedItem.chima[chima.chima] = chima.num;
                    });

                    return transformedItem;
                });
            },
		}
	}
</script>

<style lang="less" scoped>
.xzdd_content {
    height: 100vh;
	display: flex;
	flex-direction: column;
	font-size: 16rpx;

	.xzdd_header {
		width: 100%;
		padding: 15rpx 10rpx;
		box-sizing: border-box;
		
		.xzdd_header_top {
			// display: flex;
			// align-items: center;
			// border-bottom: 2rpx dashed #cbcbcb;
			// padding-bottom: 10rpx;

			.form_row {
				width: 100%;
				display: flex;
				align-items: center;


				.form_item {
					display: flex;
					align-items: center;
					padding-bottom: 20rpx;

					button {
						display: flex;
						align-items: center;
						justify-content: center;
						width: 120rpx;
						height: 40rpx;
						background: #f9a94d;
						color: #fff;
						margin: 0;
						margin-left: 10rpx;
					}
					
					.hover_btn {
						background: #da9444;
					}
				}
				
			}
		}

		.work_left {
			flex: 1;
			display: flex;
			align-items: center;

			.work_item {
				margin-right: 20rpx;
			}
		}

		.header_amount {
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #fff;
			padding-top: 20rpx;
			font-size: 20rpx;

			.amount_item {
				flex: 1;
				position: relative;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				color: #f9a94d;

				.amount_name {
					margin-bottom: 10rpx;
					font-size: 20rpx;
					color: #000;
				}

				.amount_line {
					position: absolute;
					bottom: 10rpx;
					right: 0;
					width: 2rpx;
					height: 50rpx;
					border-right: 2rpx dashed #c3c3c3;
				}
			}
		}

		.xzdd_fliter {
			display: flex;
			align-items: center;
			width: 100%;
			margin-top: 20rpx;

			.amount_num {
				flex: 1;
				margin-left: 40rpx;
				text {
					color: #ff8800;
					margin: 5rpx;
				}
			}

			.segmented {
				width: 40%;
			}
		}	
		
		.header_btns {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			margin-top: 20rpx;
		}
		button {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 120rpx;
			height: 40rpx;
			background: #f9a94d;
			color: #fff;
			margin: 0;
			margin-left: 10rpx;
		}
		
		.hover_btn {
			background: #da9444;
		}
		
		
	}

	.xzdd_list {
		flex: 1;
		overflow: auto;
		background: #f5f5f5;
		padding-top: 10rpx;
		padding-left: 5rpx;

		.billing_item {
            margin-bottom: 20rpx;
            background: #fff;
            padding: 10rpx;

            .billing_info {
                display: flex;


                .billing_img {
                    height: 90rpx;
                    width: 120rpx;
					margin-right: 10rpx;
                }

                .info_center {
                    flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-around;
					overflow: hidden;

                    .info_center_row {
                        display: flex;
                        align-items: center;

						.info_item {
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2; /* 显示三行 */
							overflow: hidden;
							text-overflow: ellipsis;
						}

                    }
                }
            }
        }

		.zdfh_list {
			margin-bottom: 20rpx;
            background: #fff;
            padding: 10rpx;

			.zdfh_header {
				display: flex;
				align-items: center;
			}


			.billing_item {
				margin-bottom: 20rpx;
				background: #fff;
				padding: 10rpx;

				.billing_info {
					display: flex;


					.billing_img {
						height: 90rpx;
						width: 120rpx;
						margin-right: 10rpx;
					}

					.info_center {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: space-around;
						overflow: hidden;

						.info_center_row {
							display: flex;
							align-items: center;

							.info_item {
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 2; /* 显示三行 */
								overflow: hidden;
								text-overflow: ellipsis;
							}

						}
					}
				}
			}
		}
	}
}
</style>
